/*
* 客户相关
* lzw
* 2021年8月4日
* */

class DlgAddRules extends RbModalHandler {
    constructor(props) {
        super(props)
        this.onView = !!window.RbViewPage
        this.state = {
            valueNum:''
        }
    }

    render() {
        return (
            <RbModal title={this.props.title || '添加新规则'} ref={(c) => (this._dlg = c)}>
                <div className="form">
                    <div className="form-group row">
                        <label className="col-sm-3 col-form-label text-sm-right">角色名</label>
                        <div className="col-sm-7">
                            {this._RolesList()}
                        </div>
                    </div>
                    <div className="form-group row">
                        <label className="col-sm-3 col-form-label text-sm-right">领取数量上线(条)</label>
                        <div className="col-sm-7">
                            <input type="number" name="value" className="form-control form-control-sm" onChange={(e)=>{this.handleChangeNum(e)}} value={this.state.valueNum} placeholder="领取数量上线(条)" />
                        </div>
                    </div>
                    <div className="form-group row footer">
                        <div className="col-sm-7 offset-sm-3" ref={(c) => (this._btns = c)}>
                            <button className="btn btn-primary btn-space" type="button" onClick={() => this.post()}>
                                {$L('Confirm')}
                            </button>
                            <a className="btn btn-link btn-space" onClick={() => this.hide()}>
                                {$L('Cancel')}
                            </a>
                        </div>
                    </div>
                </div>
            </RbModal>
        )
    }
    // 领取数量
    handleChangeNum(e){
        e.persist()
        this.setState({
            valueNum: e.target.value
        })
        // this.props.row.value = e.target.value
    }
    componentDidMount(){
        // console.log('',this.props)
        if(this.props.value){
            this.setState({
                valueNum: this.props.value
            })
        }
    }
    post(){
        // 添加规则-提交表单
        const label = this.RolesList.getSelected()
        const value = this.state.valueNum
        if(!label){
            RbHighbar.error('请填写角色名')
            return
        }
        if(!value){
            RbHighbar.error('请填写领取数量上限')
            return
        }
        const { props,props:{row} } = this
        const apiName = props.ruleId ? 'updateLeadCountRule' : 'addLeadCountRule'
        const _checked = $('#checkboxLimit').find('input[type=checkbox]').is(':checked') ? 0 : 1
        const _data = props.ruleId ? {
            ruleId: row.ruleId,
            ruleName: row.ruleName,
            entity: row.entity,
            label: label.join(),
            isDisable: row.isDisable,
            ruleCode: row.ruleCode,
            value: value
        } : {
            isDisable: _checked,
            label:label.join(),
            value:value,
            entity: props.entity
        }
        $.ajax({
            url:`/limitRule/${apiName}`,
            type:"POST",
            data:JSON.stringify(_data),
            contentType: "application/json;charset=UTF-8",
            dataType: "JSON",
            success:(res)=>{
                if(res.error_code === 0){
                    RbHighbar.success(props.ruleId ? '修改成功' : '添加成功')
                    this.hide()
                    this.getRulesList()
                }else{
                    RbHighbar.error(res.error_msg || 'error')
                }
            }
        })
    }

    /*
    * 选择角色组件
    * */
    _RolesList(){
        return <RolesList multiple={false} defaultValue={this.props.defaultValue} ruleId={this.props.ruleId} ref={(c) => (this.RolesList = c)} />
    }
    /*
    * 获取规则列表渲染
    * */
    getRulesList(){
        $.ajax({
            url:'/limitRule/selectCountRule/XnAccount',
            type:"GET",
            success:(res)=>{
                let html = ``
                const _data = res.data.data
                console.log(_data)
                const items = _data.voList
                const isDisable = _data.isDisable
                if(items.length){
                    for(let i=0;i<items.length;i++){
                        const item = items[i]
                        const itemStr = JSON.stringify(item)
                        html += `<tr>
                                    <td>${item.label}</td>
                                    <td>${item.value}</td>
                                    <td>
                                        <a href="javascript:;" class="ruleEdit" onclick='handleRuleEdit(${itemStr})'>编辑</a>
                                        <a href="javascript:;" class="ruleDelete" onclick="handleRuleDelete('${item.ruleId}')">删除</a>
                                    </td>
                                </tr>`
                    }
                }
                $('#tbodyLimit').html(html)

                $('#checkboxLimit').find('input[type=checkbox]').prop('checked',isDisable === 0 ? true : false)
            }
        })
    }

    // -- Usage
    /**
     * @param {*} props
     */
    static create(props) {

        const that = this
        console.log(that.__HOLDER)
        // if (that.__HOLDER) that.__HOLDER.show(props)
        // else
        renderRbcomp(<DlgAddRules {...props} />, null, function () {
            that.__HOLDER = this
        })

    }
}



/*
* 查询 角色列表
* */

class RolesList extends  React.Component {
    constructor(props) {
        super(props)
        this.state = { selected: props.selected || [] }
        this._cached = {}
    }
    render() {
        let inResult
        if (!this.state.items) inResult = <li className="select2-results__option un-hover text-muted">{$L('Searching')}</li>
        else if (this.state.items.length === 0) inResult = <li className="select2-results__option un-hover">{$L('NoResults')}</li>
        else {
            inResult = this.state.items.map((item) => {
                return (
                    <li key={`o-${item.roleId}`} className="select2-results__option" data-id={item.roleId} onClick={(e) => this.clickItem(e)}>
                        <i className={`zmdi ${!this.props.hideSelection && this.containsItem(item.roleId) ? ' zmdi-check' : ''}`}></i>

                        <span className="text">{item.name}</span>
                    </li>
                )
            })
        }
        const _DropdownMenu = (
            <div className="dropdown-menu">
                <div className="selector-search">
                    <div>
                        <input
                            type="search"
                            className="form-control search"
                            placeholder={$L('InputForSearch')}
                            value={this.state.query || ''}
                            ref={(c) => (this._input = c)}
                            onChange={(e) => this.searchItems(e)}
                            onKeyDown={(e) => this._keyEvent(e)}
                        />
                    </div>
                </div>
                <div className="tab-container m-0">
                    <div className="tab-content">
                        <div className="tab-pane active">
                            <div className="rb-scroller" ref={(c) => (this._scroller = c)}>
                                <ul className="select2-results__options">{inResult}</ul>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        )
        return (
            <span className="select2 select2-container select2-container--default user-selector">
                <span className="selection">
                  {this.props.compToggle ? (
                      <span ref={(c) => (this._dropdownParent = c)}>
                      {this.props.compToggle}
                          {_DropdownMenu}
                    </span>
                  ) : (
                      <div className="select2-selection select2-selection--multiple">
                          <div className="select2-selection__rendered" ref={(c) => (this._dropdownParent = c)}>
                              {this.state.selected.length > 0 && (
                                  <span className="select2-selection__clear" onClick={() => this.clearSelection()}>
                            &times;
                          </span>
                              )}
                              {this.state.selected.map((item) => {
                                  return (
                                      <span key={`s-${item.roleId}`} className="select2-selection__choice">
                              <span className="select2-selection__choice__remove" data-id={item.roleId} onClick={(e) => this.removeItem(e)}>
                                &times;
                              </span>{' '}
                                          {item.name}
                            </span>
                                  )
                              })}
                              <span className="select2-selection__choice abtn" data-toggle="dropdown">
                          <a>
                            <i className="zmdi zmdi-plus" /> {this.props.multiple === false ? $L('Select') : $L('Add')}
                          </a>
                        </span>
                              {_DropdownMenu}
                          </div>
                      </div>
                  )}
                </span>
            </span>
        )
    }
    getRolesList(name='',roleId=null){
        $.ajax({
            url:`/commonSearch/selectRoleList?name=${name}`,
            type:'GET',
            success: (res)=> {
                if (res.error_code === 0 && res.data.data.length > 0) {
                    this.setState({ items: res.data.data,isDisabled:res.data.data[0].isDisable })
                    console.log('roleId',roleId)
                    if(roleId!=null){
                        console.log('res.data.data',res.data.data)
                        this.setState({
                            selected: res.data.data
                        })
                    }
                }
            }
        })
    }
    componentDidMount() {
        $(this._scroller).perfectScrollbar()

        const that = this
        $(this._dropdownParent).on({
            'show.bs.dropdown': function () {
                // 初始化
                if (!that.state.items) that.getRolesList()
            },
            'shown.bs.dropdown': function () {
                that._input && that._input.focus()
                $(that._scroller).find('li.active').removeClass('active')
            },
            'hide.bs.dropdown': function (e) {
                if (!e.clickEvent || !e.clickEvent.target) return
                const $target = $(e.clickEvent.target)
                if ($target.hasClass('dropdown-menu') || $target.parents('.dropdown-menu').length === 1) {
                    if (that.props.multiple === false) {
                        if (!($target.hasClass('select2-results__options') || $target.parents('.select2-results__options').length === 1)) return false
                    } else {
                        return false
                    }
                }
            },
        })
        if (this.props.defaultValue) {
            this.getRolesList(this.props.defaultValue,this.props.ruleId)
        }
    }

    componentWillUnmount() {
        $(this._scroller).perfectScrollbar('destroy')
    }

    UNSAFE_componentWillReceiveProps(props) {
        this.setState({ selected: props.selected || this.state.selected })
    }

    clearSelection() {
        this.setState({ selected: [] }, () => {
            typeof this.props.onClearSelection === 'function' && this.props.onClearSelection()
        })
    }

    _tryActive($active, $el) {
        if ($el && $el.length === 1) {
            $active.removeClass('active')
            $el.addClass('active')

            const st = $(this._scroller).scrollTop()
            const et = $el.position().top
            if (et >= 0) {
                const top = et + st - (222 - 36) // maxHeight - elementHeight
                if (top > 0) $(this._scroller).scrollTop(top)
            } else {
                const top = st + et
                if (top >= 0) $(this._scroller).scrollTop(top)
            }
        }
    }

    _keyEvent(e) {
        if (e.keyCode === 40) {
            const $active = $(this._scroller).find('li.active')
            const $next = $active.length === 0 ? $(this._scroller).find('li:eq(0)') : $active.next()
            this._tryActive($active, $next)
        } else if (e.keyCode === 38) {
            const $active = $(this._scroller).find('li.active')
            const $prev = $active.length === 0 ? null : $active.prev()
            this._tryActive($active, $prev)
        } else if (e.keyCode === 13) {
            const $active = $(this._scroller).find('li.active')
            if ($active.length === 1) {
                $active.trigger('click')
                $stopEvent(e)
            }
        }
    }

    searchItems(e) {
        this.setState({ query: e.target.value }, () => {
            this.getRolesList(this.state.query)
        })
    }

    clickItem(e, isRemove) {
        const $target = $(e.currentTarget)
        const id = $target.data('id') || $target.parents('.select2-results__option').data('id')

        let exists = false
        let ns = []
        // 单选
        if (this.props.multiple !== false || isRemove) {
            ns = this.state.selected.filter((x) => {
                if (x.roleId === id) {
                    exists = true
                    return false
                }
                return true
            })
        }

        const selected = { roleId: id, name: $target.text() }

        if (!exists) ns.push(selected)
        if (ns.length >= 20) {
            RbHighbar.create($L('MaxSelectX').replace('%d', 20))
            return false
        }

        this.setState({ selected: ns }, () => {
            typeof this.props.onSelectItem === 'function' && this.props.onSelectItem(selected, isRemove)
        })
    }

    removeItem(e) {
        this.clickItem(e, true)
    }

    containsItem(id) {
        return !!this.state.selected.find((x) => x.roleId === id)
    }

    getSelected() {
        const ids = []
        this.state.selected.forEach((item) => ids.push(item.roleId))
        return ids
    }

    val() {
        return this.getSelected()
    }
}


/*
* 删除规则
* */
class RulesDeleteConfirm extends RbAlert {
    constructor(props) {
        super(props)
        this.state = { enableCascades: false }
    }

    render() {
        let message = this.props.message
        if (!message) message = this.props.ids ? $L('DeleteSelectedSomeConfirm').replace('%d', this.props.ids.length) : $L('DeleteRecordConfirm')

        return (
            <div className="modal rbalert" ref={(c) => (this._dlg = c)} tabIndex="-1">
                <div className="modal-dialog modal-dialog-centered">
                    <div className="modal-content">
                        <div className="modal-header pb-0">
                            <button className="close" type="button" onClick={() => this.hide()}>
                                <span className="zmdi zmdi-close" />
                            </button>
                        </div>
                        <div className="modal-body">
                            <div className="text-center ml-6 mr-6">
                                <div className="text-danger">
                                    <span className="modal-main-icon zmdi zmdi-alert-triangle" />
                                </div>
                                <div className="mt-3 text-bold">{message}</div>
                                <div className="mt-4 mb-3" ref={(c) => (this._btns = c)}>
                                    <button className="btn btn-space btn-secondary" type="button" onClick={() => this.hide()}>
                                        {$L('Cancel')}
                                    </button>
                                    <button className="btn btn-space btn-danger" type="button" onClick={() => this.handleDelete()}>
                                        {$L('Delete')}
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        )
    }

    handleDelete() {
        let ids = this.props.ids || this.props.id
        if (!ids || ids.length === 0) return
        if (typeof ids === 'object') ids = ids.join(',')
        const $btns = $(this._btns).find('.btn').button('loading')
        $.post(`/limitRule/deleteCountRule?id=${ids}`, (res) => {
            if (res.error_code === 0) {
                RbHighbar.success('删除成功')

                this.hide()
                typeof this.props.deleteAfter === 'function' && this.props.deleteAfter()
            } else {
                RbHighbar.error(res.error_msg)
                $btns.button('reset')
            }
        })
    }
}